package com.bxs.detector.impl;

import com.bxs.detector.BaseDetector;
import com.bxs.global.LogLevel;
import com.bxs.pojo.DangerMsg;
import com.bxs.pojo.BaseRule;
import lombok.extern.slf4j.Slf4j;
import org.pcap4j.core.PcapPacket;
import org.pcap4j.packet.IcmpV4CommonPacket;
import org.pcap4j.packet.IpV4Packet;
import org.pcap4j.packet.TcpPacket;
import org.pcap4j.packet.namednumber.IpNumber;

import java.util.List;

/**
 * @author dream
 * @title: ProtocolFieldDector
 * @projectName ids_v0_2
 * @description: TODO
 */
// 协议字段检测
@Slf4j
public class ProtocolFieldDetector extends BaseDetector {
    @Override
    public DangerMsg detect(PcapPacket packet, List<BaseRule> rules) {
        System.out.println("ProtocolFieldDetector execute");
        // 只处理ipv4
        IpV4Packet ipV4Packet =  packet.get(IpV4Packet.class);
        if(ipV4Packet == null){
            System.out.println("get packet not is ipv4");
            return null;
        }
        // 获取数据包协议字段
        IpV4Packet.IpV4Header header = ipV4Packet.getHeader();
        IpNumber protocol = header.getProtocol();
        DangerMsg msg = new DangerMsg();
        msg.setCode(LogLevel.WARNING.getCode());
        msg.setDesc("protocol: " + protocol.name());
        msg.setSourceIp(header.getSrcAddr().getHostAddress());
        msg.setTargetIp(header.getDstAddr().getHostAddress());
        System.out.println("protocol detect: " + msg);
        // 各种协议处理
        if (protocol.name().equals(IpNumber.ICMPV4.name())){
            System.out.println("icmp packet");
            // ICMP报文处理
//            IcmpV4CommonPacket icmpV4CommonPacket = packet.get(IcmpV4CommonPacket.class);
            for (BaseRule rule : rules){
                if (rule.getProtocolType().equals(IpNumber.ICMPV4.name())){
                    System.out.println("icmp packet, warning...");
                    msg.setCode(rule.getLevel());   // 警告策略
                    msg.setPacket(packet);
                    return msg;
                }
            }

        }else if(protocol.name().equals(IpNumber.TCP.name())){
            // TCP报文处理
            TcpPacket tcpPacket = ipV4Packet.get(TcpPacket.class);
//            packet.get()
            TcpPacket.TcpHeader tcpHeader = tcpPacket.getHeader();
            msg.setSourcePort(tcpHeader.getSrcPort().valueAsInt());
            msg.setTargetPort(tcpHeader.getDstPort().valueAsInt());
            System.out.println("packet info:" + msg);
            for(BaseRule rule : rules){
                System.out.println("ProtocolFieldDetector: " + rule.getProtocolType() + " ; " + protocol.name());
                // 协议额类型检测
                if(rule.getProtocolType().equals(protocol.name())){
                    msg.setPacket(packet);
                    return msg;
                }
            }
        }

        return null;
    }
}
